//
//  NetManager.m
//  03-28-net2
//
//  Created by student on 16/3/29.
//  Copyright © 2016年 niit. All rights reserved.
//

#import "NetManager.h"
#import "def.h"
#import "Video.h"
@implementation NetManager






+(BOOL)loginWithUserName:(NSString *)username andPassword:(NSString *)password
{
    //请求地址的字符串
    NSString *str=[NSString stringWithFormat:@"http://192.168.13.31:8080/MJServer/login?username=%@&pwd=%@&method=get&type=JSON",username,password];
    
    //请求网址
    NSURL *url=[NSURL URLWithString:str];
    //请求
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    //发送同步请求
    NSData *data =[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",result);
    // 数据解析
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    
    //{"success":"登录成功"}
    //{"error":"密码不正确"}
    
    if (dict[@"error"]!=nil) {
        return  NO;
    }
    else{
        return YES;
    }
}



//+(void)loginWithUserName:(NSString *)username
//             andPassword:(NSString *)password
//            successBlock:(void (^)())successBlock
//             failedBlock:(void (^)())failBlock
//{
//    // 请求地址的字符串
//    NSString *str = [NSString stringWithFormat:@"http://192.168.13.28:8080/MJServer/login?username=%@&pwd=%@&method=get&type=JSON",username,password];
//    // 请求网址
//    NSURL *url = [NSURL URLWithString:str];
//    // 请求
//    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
//    
//    // 发送异步请求
//    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//        
//        if(connectionError == nil)
//        {
//            NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//            NSLog(@"%@",result);
//            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//            
//            //{"success":"登录成功"}
//            //{"error":"密码不正确"}
//            if(dict[@"error"]!=nil)
//            {
//                //执行失败时要执行block代码
//                failBlock();
//                
//            }
//            else
//            {
//                //成功时的block
//                successBlock();
//            
//            }
//        }
//        else
//        {
//            failBlock();
//        }
//    }];
//}



+(void)loginWithUserName:(NSString *)username
              andPassword:(NSString *)password
             successBlock:(void (^)())successBlock
              failedBlock:(void (^)(NSError *))failBlock
{
    // 请求地址的字符串
    NSString *str = [NSString stringWithFormat:@"http://192.168.13.28:8080/MJServer/login?username=%@&pwd=%@&method=get&type=JSON",username,password];
    
    [self requestInfoWithURLStr:str
                   successBlock:^(NSData *data) {
                       // 处理数据
                       NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                       if(dict[@"error"] != nil)
                       {
                           // 定义一个NSError对象
                           NSError *error = [NSError errorWithDomain:@"com.niit.net2Demo"                           // 域
                                                                code:kErrorLogin                                    // 错误编号
                                                            userInfo:@{NSLocalizedDescriptionKey:dict[@"error"]}];  // 错误信息
                           // 执行fail时block代码
                           failBlock(error);
                       }
                       else
                       {
                           // 执行成功时block代码
                           successBlock();
                       }
                   } faileBlock:^(NSError *error) {
                       // 执行fail时block代码
                       failBlock(error);
                   }];
}

/**
 *  获取电影列表
 *
 *  @param successBock 获取成功时执行的block
 *  @param failBlock   获取失败时执行的block
 */
+ (void)requestMovieListWithSuccessBlock:(void (^)(NSArray *))successBock
                             failedBlock:(void (^)(NSError *))failBlock
{
    //请求地址的字符串
    NSString *str=@"http://192.168.13.31:8080/MJServer/video?method=get&type=JSON";
    
    //请求网址
    NSURL *url =[NSURL URLWithString:str];
    //请求
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    //发送异步请求
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError==nil) {
            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSArray *arr=dict[@"videos"];
            NSMutableArray *mArr=[NSMutableArray array];
            
            for (NSDictionary *d in arr) {
                Video *v=[Video videoWithDict:d];
                [mArr addObject:v];
            }
            successBock(mArr);
        }
        else
        {
            //连接失败
            failBlock();
        }
        
    }];

}


/**
 *  请求数据
 *
 *  @param urlStr       请求网址
 *  @param successBlock 请求成功时执行的block
 *  @param failBlock    获取失败时执行的block
 */
+(void)requestInfoWithURLStr:(NSString *)urlStr
                successBlock:(void (^)(NSData *))successBlock
                  faileBlock:(void (^)(NSError *))failBlock
{
    // 请求网址
    NSURL *url = [NSURL URLWithString:urlStr];
    // 请求
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    // 发送异步请求
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if(connectionError == nil)
        {
            // 请求成功
            successBlock(data);
        }
        else
        {
            // 请求失败
            failBlock(connectionError);
        }
        
    }];
}



//委托模式(代理)
//单例
SingletonM(NetManager)

-(void)loginWithUserName:(NSString *)username
             andPassword:(NSString *)password
{
    // 请求地址的字符串
    NSString *str = [NSString stringWithFormat:@"http://192.168.13.28:8080/MJServer/login?username=%@&pwd=%@&method=get&type=JSON",username,password];
    
    [self requestInfoWithURLStr:str
                   successBlock:^(NSData *data) {
                       // 处理数据
                       NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
                       if(dict[@"error"] != nil)
                       {
                           // 定义一个NSError对象
                           NSError *error = [NSError errorWithDomain:@"com.niit.net2Demo"                           // 域
                                                                code:kErrorLogin                                    // 错误编号
                                                            userInfo:@{NSLocalizedDescriptionKey:dict[@"error"]}];  // 错误信息
                           
                           //发送成功时的通知（观察者模式）
                           [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationLoginFail object:nil userInfo:@{@"error":error}];
                           // 执行fail时block代码(委托模式)
                           [self.delegate loginfailed:error];
                           
                       }
                       else
                       {
                           //发送成功时的通知（观察者模式）
                           [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationLoginSuccess object:nil userInfo:nil];
                           
                           // 执行成功时block代码(委托模式)
                           [self.delegate loginsuccess];
                       }
                   } faileBlock:^(NSError *error) {
                       
                       //发送失败时的通知（观察者模式）
                       [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationLoginFail object:nil userInfo:@{@"error":error}];
                       // 执行fail时block代码(委托模式)
                       [self.delegate loginfailed:error];
                   }];

}
-(void)requestInfoWithURLStr:(NSString *)urlStr
                successBlock:(void (^)(NSData *))successBlock
                  faileBlock:(void (^)(NSError *))failBlock
{
    // 请求网址
    NSURL *url = [NSURL URLWithString:urlStr];
    // 请求
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    // 发送异步请求
    [NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if(connectionError == nil)
        {
            // 请求成功
            successBlock(data);
        }
        else
        {
            // 请求失败
            failBlock(connectionError);
        }
        
    }];
}

@end
